package com.jinzhi.jzweb.controller;



import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.domain.DictDO;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.pojo.ExtraOrderVO;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.sms.support.SmsManager;
import com.jinzhi.sys.domain.RoleDO;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.domain.UserRoleDO;
import com.jinzhi.sys.service.RoleService;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * <pre>
 * 额外订单订单记录表
 * </pre>
 * <small> 2021-04-08 09:00:12 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/extraOrder")
public class ExtraOrderController extends BaseController {


    @Autowired
    private BookStockService bookStockService;

    @Autowired
    private ExtraOrderService extraOrderService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private BookOrderService bookOrderService;


    @Autowired
    private BookPurchaseService bookPurchaseService;

    @Autowired
    private MessageplatfromService messageplatfromService;

    @Autowired
    private SmsManager smsSerevice;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;

    @GetMapping()
    @RequiresPermissions("jzweb:extraOrder:extraOrder")
    String ExtraOrder(){
        return "jzweb/extraOrder/extraOrder";
    }


    @GetMapping("/add")
    @RequiresPermissions("jzweb:extraOrder:add")
    String add(Model model){
        List <Map> mapList=new ArrayList<>();
//        Map map=new HashMap();
//        map.put("name","物料包");
//        mapList.add(map);
//        Map map2=new HashMap();
//        map2.put("name","仪器");
//        mapList.add(map2);
        Map map=new HashMap();
        map.put("name","其它物品");
        mapList.add(map);
        model.addAttribute("list",mapList);
        return "jzweb/extraOrder/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("jzweb:extraOrder:edit")
    String edit(@PathVariable("id") Long id, Model model){
        ExtraOrderDO extraOrder = extraOrderService.selectById(id);
        model.addAttribute("extraOrder", extraOrder);
        return "jzweb/extraOrder/edit";
    }


    @GetMapping("/examineCk/{id}")
    @RequiresPermissions("jzweb:extraOrder:examineCk")
    String examineCk(@PathVariable("id") Long id,Model model){
        ExtraOrderDO extraOrder = extraOrderService.selectById(id);
        model.addAttribute("extraOrder", extraOrder);
        return "jzweb/extraOrder/examineCk";
    }



    /**
     * 下单
     * @param
     * @return
     */
    @Log("下单")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("jzweb:extraOrder:add")
    @Transactional
    public Result<String> save(ExtraOrderDO extraOrderDO){
        int orderNumber = extraOrderDO.getOrderNumber(); //订单数量
        BigDecimal orderMoney = new BigDecimal(0.0); //订单价格

        List<String> bookId = splitStrArrayList(extraOrderDO.getBookId()); //将多个订单id转换为数组
        if (bookId.size()>=3){
            return Result.fail("请勿选择多个物品");
        }

        for (int i=1;i<=(bookId.size()-1);i++){

            BookStockDO bookStockDO = bookStockService.selectById(bookId.get(i));
            if (bookStockDO.getStockNum() == null){
                bookStockDO.setStockNum(0);
            }
            if (bookStockDO.getStockNum()<orderNumber){
                return Result.fail("库存不足请补充！");
            }

            orderMoney = bookStockDO.getMoney(); //单价
            orderMoney=(BigDecimal.valueOf(orderNumber).multiply(orderMoney)); //计算价格
            //下单初始化数据
            extraOrderDO.setOrderMoney(orderMoney);//订单价格
            extraOrderDO.setOrderCreatetime(new Date());//下单时间
            extraOrderDO.setCreareUser(this.getUserId()); //创建人id
            extraOrderService.insert(extraOrderDO);//向额外订单表中添加数据。

            bookStockDO.setStockNum(bookStockDO.getStockNum() -  orderNumber);
            if (bookStockDO.getSalesVolume()==null){
                bookStockDO.setSalesVolume(0);
            }
            bookStockDO.setSalesVolume(bookStockDO.getSalesVolume() + orderNumber);
            bookStockService.updateById(bookStockDO);//修改库存表
        }
        return Result.ok();
    }


    //将字符串以，隔开为集合。
    private List<String> splitStrArrayList(String str) {
        List<String> stringList = new ArrayList<>();
        if (str != null) {
            String[] strs = str.split(",");
            stringList.addAll(Arrays.asList(strs));
            return stringList;
        }
        return null;
    }


    /**
     * 查询物料包
     * @return
     */
    @Log("物料包查询")
    @ResponseBody
    @GetMapping("/selectBookType")
    public Result<List<BookStockDO>> selectBookType(String type){
        EntityWrapper<BookStockDO> wrapper = new EntityWrapper<>();
        wrapper.eq("book_types",type);
        List<BookStockDO> bookStockDOS = bookStockService.selectList(wrapper);
        return Result.ok(bookStockDOS);
    }


    /**
     * 查询额外订单列表
     */
    @Log("查询订单列表")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("jzweb:extraOrder:extraOrder")
    public Result<Page<ExtraOrderDO>> list(ExtraOrderDO extraOrderDO){
        EntityWrapper<ExtraOrderDO> entityWrapper =new EntityWrapper<>();

        if (StringUtil.notEmpty(extraOrderDO.getProvince())){ //根据省份查询
            entityWrapper.eq("province",extraOrderDO.getProvince());
        }

        if (null != extraOrderDO.getAddressee()){ //根据收件人查询
            entityWrapper.eq("addressee",extraOrderDO.getAddressee());
        }

        if (null != extraOrderDO.getYear()){ //根据年份查询
            entityWrapper.eq("year",extraOrderDO.getYear());
        }


        Integer is=	userRoleService.userRolenum(this.getUserId());
        if (is == 8 || is == 9){
            entityWrapper.eq("creare_user",extraOrderDO.getCreareUser());
        }
        Page<ExtraOrderDO> extraOrderDOPage = extraOrderService.selectPage(getPage(ExtraOrderDO.class),entityWrapper);
        for (int i=0;i<extraOrderDOPage.getRecords().size();i++){
            List<String> list = splitStrArrayList(extraOrderDOPage.getRecords().get(i).getBookId());
            String name = "";
            for (int j = 1;j<list.size();j++){
                BookStockDO bookStockDO = bookStockService.selectById(list.get(j));
                if (bookStockDO != null){
                    if (name.equals("")) {
                        name = bookStockDO.getBookType() == null ? "" : bookStockDO.getBookType();
                    } else {
                        name = name + "," + bookStockDO.getBookType() == null ? "" : bookStockDO.getBookType();
                    }
                }
            }
            extraOrderDOPage.getRecords().get(i).setName(name);
        }
        return Result.ok(extraOrderDOPage);
    }



    @Log("删除订单记录表")
    @PostMapping( "/remove")
    @ResponseBody
    @Transactional
    @RequiresPermissions("jzweb:extraOrder:remove")
    public Result<String> remove(Long id){
        inventoryRestore(id); //删除之前先还原库存
        extraOrderService.deleteById(id);
        return Result.ok();
    }



    @Log("批量删除订单记录表")
    @PostMapping( "/batchRemove")
    @ResponseBody
    @Transactional
    @RequiresPermissions("jzweb:extraOrder:batchRemove")
    public Result<String>  batchRemove(@RequestParam("ids[]") Long[] ids){
        for (int i=0;i<ids.length;i++){ //删除之前先还原库存
            inventoryRestore(ids[i]);
        }
        extraOrderService.deleteBatchIds(Arrays.asList(ids));
        return Result.ok();
    }

    //库存还原方法
    private void inventoryRestore(Long id){
        ExtraOrderDO extraOrderDO = extraOrderService.selectById(id);
        String bookId = extraOrderDO.getBookId();
        List<String> list = splitStrArrayList(bookId);
        for (int i=1;i<=(list.size()-1);i++){
            BookStockDO bookStockDO = bookStockService.selectById(list.get(i));
            bookStockDO.setSalesVolume(bookStockDO.getSalesVolume() - extraOrderDO.getOrderNumber());
            bookStockDO.setStockNum(bookStockDO.getStockNum() + extraOrderDO.getOrderNumber());
            bookStockService.updateById(bookStockDO);
        }
    }


    /**
     * 查询所有学校信息
     * @return
     */
    @GetMapping("/selectSchool")
    @ResponseBody
    @Log("查询考试批次信息")
    public  Result<?> selectSchool(@RequestParam(required = false,defaultValue = "1")int pageNumber, @RequestParam(required = false,defaultValue = "10")int pageSize, String name){
        Page<Map<Object,Object>> list=bookOrderService.selectSchool(pageNumber,pageSize,name);
        return Result.ok(list);
    }





    @Log("选择导出")
    @GetMapping("/orderExportListIds")
    @ResponseBody
    @Transactional
    @RequiresPermissions("jzweb:extraOrder:export")
    public void orderExportListIds(HttpServletRequest request, HttpServletResponse response, @RequestParam("ids[]") Long[] ids) throws Exception{

        List<ExtraOrderDO> extraOrderDOS = extraOrderService.selectBatchIds(Arrays.asList(ids));
        List<ExtraOrderVO> list = new ArrayList();
        for (int i = 0; i < extraOrderDOS.size(); i++) {
            ExtraOrderDO obj = extraOrderDOS.get(i);

            ExtraOrderVO extraOrderVO=new ExtraOrderVO();

            extraOrderVO.setDistrict(obj.getDistrict()); //县区
            extraOrderVO.setAddress(obj.getAddress()); //详细地址
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            extraOrderVO.setStartTime(sdf.format(obj.getOrderCreatetime())); //下单时间
            extraOrderVO.setCity(obj.getCity());//市
            extraOrderVO.setProvince(obj.getProvince());//省份
            extraOrderVO.setOrderNumber(obj.getOrderNumber()); //订单数量
            extraOrderVO.setOrderMoney(obj.getOrderMoney()); //订单价格
            extraOrderVO.setMobile(obj.getMobile()); //联系人电话
            extraOrderVO.setId(obj.getId()); //订单编号

            extraOrderVO.setYear(obj.getYear()); //年份
            list.add(extraOrderVO);
        }
        EasyPoiUtil.exportExcel(list, "选择订单记录", "选择订单记录", ExtraOrderVO.class,"进销存订单记录表",response);
    }






}